<template>
  <a-card :bordered="false">
    <!-- 查询区域 -->
    <div class="table-page-search-wrapper">
      <a-form layout="inline" @keyup.enter.native="searchQuery">
        <a-row :gutter="24">
          <a-col :md="6" :sm="8">
            <a-form-item label="真实姓名">
              <a-input placeholder="请输入真实姓名" v-model="queryParam.realName"></a-input>
            </a-form-item>
          </a-col>
          <a-col :md="6" :sm="8">
            <a-form-item label="昵称">
              <a-input placeholder="请输入昵称" v-model="queryParam.nickname"></a-input>
            </a-form-item>
          </a-col>
          <a-col :md="6" :sm="8">
            <a-form-item label="技术栈">
              <a-select
                mode="multiple"
                placeholder="请选择技术栈"
                v-model="queryParam.stacks"
                allowClear>
                <a-select-option v-for="item in stacksDict.items" :key="item.value" :value="item.value">
                  {{ item.text }}
                </a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
          <a-col :md="6" :sm="8">
            <a-form-item label="联系电话">
              <a-input placeholder="请输入联系电话" v-model="queryParam.phone"></a-input>
            </a-form-item>
          </a-col>
          <template v-if="toggleSearchStatus">
            <a-col :md="6" :sm="8">
              <a-form-item label="微信账号">
                <a-input placeholder="请输入微信账号" v-model="queryParam.wechatAccount"></a-input>
              </a-form-item>
            </a-col>
            <a-col :md="6" :sm="8">
              <a-form-item label="支付宝账号">
                <a-input placeholder="请输入支付宝账号" v-model="queryParam.alipayAccount"></a-input>
              </a-form-item>
            </a-col>
          </template>
          <a-col :md="6" :sm="8">
            <span style="float: left;overflow: hidden;" class="table-page-search-submitButtons">
              <a-button type="primary" @click="searchQuery" icon="search">查询</a-button>
              <a-button type="primary" @click="searchReset" icon="reload" style="margin-left: 8px">重置</a-button>
              <a @click="handleToggleSearch" style="margin-left: 8px">
                {{ toggleSearchStatus ? '收起' : '展开' }}
                <a-icon :type="toggleSearchStatus ? 'up' : 'down'"/>
              </a>
            </span>
          </a-col>
        </a-row>
      </a-form>
    </div>
    <!-- 操作按钮区域 -->
    <div class="table-operator">
      <a-button @click="handleAdd" type="primary" icon="plus">新增</a-button>
      <a-button type="primary" icon="download" @click="handleExportXls('程序员信息')">导出</a-button>
      <a-upload name="file" :showUploadList="false" :multiple="false" :headers="tokenHeader" :action="importExcelUrl" @change="handleImportExcel">
        <a-button type="primary" icon="import">导入</a-button>
      </a-upload>
      <a-dropdown v-if="selectedRowKeys.length > 0">
        <a-menu slot="overlay">
          <a-menu-item key="1" @click="batchDel"><a-icon type="delete"/>删除</a-menu-item>
        </a-menu>
        <a-button style="margin-left: 8px"> 批量操作 <a-icon type="down" /></a-button>
      </a-dropdown>
    </div>

    <!-- table区域-begin -->
    <div>
      <div class="ant-alert ant-alert-info" style="margin-bottom: 16px;">
        <i class="anticon anticon-info-circle ant-alert-icon"></i> 已选择 <a style="font-weight: 600">{{ selectedRowKeys.length }}</a>项
        <a style="margin-left: 24px" @click="onClearSelected">清空</a>
      </div>

      <!-- 总利润统计 -->
      <div class="profit-summary" v-if="totalProfit > 0">
        <a-alert type="success" show-icon>
          <template slot="message">
            <span class="profit-text">总利润: <a style="font-weight: 600">{{ totalProfit.toFixed(2) }}</a> 元</span>
          </template>
        </a-alert>
      </div>

      <a-table
        ref="table"
        size="middle"
        bordered
        rowKey="id"
        :columns="columns"
        :dataSource="dataSource"
        :pagination="ipagination"
        :loading="loading"
        :rowSelection="{selectedRowKeys: selectedRowKeys, onChange: onSelectChange}"
        @change="handleTableChange">

        <template slot="stacksSlot" slot-scope="text">
          <span v-if="!text"></span>
          <template v-else>
            <a-tag 
              v-for="stack in getStacksArray(text)" 
              :key="stack" 
              :color="getStackColor(stack)"
              style="margin-bottom: 4px;">
              {{ getStackText(stack) }}
            </a-tag>
          </template>
        </template>
        <span slot="action" slot-scope="text, record">
          <a @click="handleEdit(record)">编辑</a>
          <a-divider type="vertical" />
          <a-dropdown>
            <a class="ant-dropdown-link">更多 <a-icon type="down" /></a>
            <a-menu slot="overlay">
              <a-menu-item>
                <a-popconfirm title="确定删除吗?" @confirm="() => handleDelete(record.id)">
                  <a>删除</a>
                </a-popconfirm>
              </a-menu-item>
            </a-menu>
          </a-dropdown>
        </span>
      </a-table>
    </div>
    <!-- table区域-end -->

    <!-- 表单区域 -->
    <bProgrammerInfo-modal ref="modalForm" @ok="modalFormOk"></bProgrammerInfo-modal>
  </a-card>
</template>

<script>
  import BProgrammerInfoModal from './modules/BProgrammerInfoModal'
  import { JeecgListMixin } from '@/mixins/JeecgListMixin'
  import JDictSelectTag from '@/components/dict/JDictSelectTag'
  import { getAction } from '@/api/manage'

  export default {
    name: "BProgrammerInfoList",
    mixins:[JeecgListMixin],
    components: {
      BProgrammerInfoModal,
      JDictSelectTag
    },
    data () {
      return {
        description: '程序员信息管理页面',
        // 表头
        columns: [
          {
            title: '#',
            dataIndex: '',
            key:'rowIndex',
            width:60,
            align:"center",
            customRender:function (t,r,index) {
              return parseInt(index)+1;
            }
          },
          {
            title: '真实姓名',
            align:"center",
            dataIndex: 'realName'
          },
          {
            title: '昵称',
            align:"center",
            dataIndex: 'nickname'
          },
          {
            title: '微信账号',
            align:"center",
            dataIndex: 'wechatAccount'
          },
          {
            title: '支付宝账号',
            align:"center",
            dataIndex: 'alipayAccount'
          },
          {
            title: '联系电话',
            align:"center",
            dataIndex: 'phone'
          },
          {
            title: '技术栈',
            align:"center",
            dataIndex: 'stacks',
            scopedSlots: { customRender: 'stacksSlot' }
          },
          {
            title: '程序价格(元)',
            align:"center",
            dataIndex: 'programPrice'
          },
          {
            title: '论文价格(元)',
            align:"center",
            dataIndex: 'paperPrice'
          },
          {
            title: '操作',
            dataIndex: 'action',
            align:"center",
            scopedSlots: { customRender: 'action' },
            width: 150
          }
        ],
        url: {
          list: "/order/bProgrammerInfo/list",
          delete: "/order/bProgrammerInfo/delete",
          deleteBatch: "/order/bProgrammerInfo/deleteBatch",
          exportXlsUrl: "/order/bProgrammerInfo/exportXls",
          importExcelUrl: "/order/bProgrammerInfo/importExcel",
        },
        dictOptions:{},
        superFieldList:[],
        // 技术栈字典缓存
        stacksDict: {
          items: [],
          map: {}
        },
        // 总利润
        totalProfit: 0,
        // 自定义分页配置
        ipagination: {
          current: 1,
          pageSize: 50,
          pageSizeOptions: ['50', '100', '200', '500'],
          showTotal: (total, range) => {
            return range[0] + "-" + range[1] + " 共" + total + "条";
          },
          showQuickJumper: true,
          showSizeChanger: true,
          total: 0
        }
      }
    },
    created() {
      this.getSuperFieldList();
      this.loadStacksDict();
      // 不再需要在这里设置默认分页大小，因为已经在data中设置了
    },
    computed: {
      importExcelUrl: function(){
        return `${window._CONFIG['domianURL']}/${this.url.importExcelUrl}`;
      }
    },
    methods: {
      initDictConfig(){
      },
      getSuperFieldList(){
        let fieldList=[];
        fieldList.push({type:'string',value:'realName',text:'真实姓名',dictCode:''})
        fieldList.push({type:'string',value:'nickname',text:'昵称',dictCode:''})
        fieldList.push({type:'string',value:'wechatAccount',text:'微信账号',dictCode:''})
        fieldList.push({type:'string',value:'alipayAccount',text:'支付宝账号',dictCode:''})
        fieldList.push({type:'string',value:'phone',text:'联系电话',dictCode:''})
        fieldList.push({type:'string',value:'stacks',text:'技术栈',dictCode:'stacks'})
        fieldList.push({type:'double',value:'programPrice',text:'程序价格(元)',dictCode:''})
        fieldList.push({type:'double',value:'paperPrice',text:'论文价格(元)',dictCode:''})
        fieldList.push({type:'string',value:'remark',text:'备注',dictCode:''})
        this.superFieldList = fieldList
      },
      // 加载技术栈字典
      loadStacksDict() {
        const that = this;
        getAction('/sys/dict/getDictItems/stacks').then(res => {
          if (res.success) {
            that.stacksDict.items = res.result;
            // 构建映射表，方便查询
            const map = {};
            res.result.forEach(item => {
              map[item.value] = {
                text: item.text,
                color: item.description || 'default' // 使用描述字段存储颜色
              };
            });
            that.stacksDict.map = map;
          }
        });
      },
      // 将技术栈字符串转换为数组
      getStacksArray(stacks) {
        if (!stacks) return [];
        return stacks.split(',');
      },
      // 获取技术栈文本
      getStackText(stack) {
        return (this.stacksDict.map[stack] && this.stacksDict.map[stack].text) || stack;
      },
      // 获取技术栈颜色
      getStackColor(stack) {
        return (this.stacksDict.map[stack] && this.stacksDict.map[stack].color) || 'default';
      },
      // 重写搜索方法，处理技术栈多选
      searchQuery() {
        let params = Object.assign({}, this.queryParam);
        // 处理技术栈多选
        if (params.stacks && Array.isArray(params.stacks) && params.stacks.length > 0) {
          params.stacks = params.stacks.join(',');
        }
        this.loadData(1, params);
      },
      // 获取订单类型颜色
      getOrderTypeColor(type) {
        // 根据订单类型设置不同的颜色
        switch(type) {
          case '1': return 'blue';       // 毕设全包
          case '2': return 'purple';     // 单程序
          case '3': return 'cyan';       // 单论文
          case '4': return 'geekblue';   // 二开
          case '5': return 'green';      // 项目部署
          default: return 'default';
        }
      },
      
      // 计算总利润
      calculateTotalProfit(programmerId) {
        const that = this;
        // 构建查询参数
        const params = {
          programmerId: programmerId,
          pageNo: 1,
          pageSize: 500 // 设置较大的数值以获取所有订单
        };
        
        // 调用订单查询接口
        getAction('/order/bOrderInfo/list', params).then(res => {
          if (res.success) {
            // 计算总利润
            let profit = 0;
            if (res.result && res.result.records) {
              res.result.records.forEach(order => {
                profit += Number(order.profit || 0);
              });
            }
            that.totalProfit = profit;
          }
        });
      },
      
      // 重写loadData方法，添加总利润计算
      loadData(arg) {
        if (arg === 1) {
          this.ipagination.current = 1;
        }
        const params = this.getQueryParams();
        this.loading = true;
        getAction(this.url.list, params).then((res) => {
          if (res.success) {
            this.dataSource = res.result.records || [];
            this.ipagination.total = res.result.total || 0;
            
            // 如果只有一个程序员，计算其总利润
            if (this.dataSource.length === 1) {
              this.calculateTotalProfit(this.dataSource[0].id);
            } else {
              this.totalProfit = 0; // 重置总利润
            }
          }
          if(res.code===510){
            this.$message.warning(res.message)
          }
          this.loading = false;
        })
      },
    }
  }
</script>
<style scoped>
  @import '~@assets/less/common.less';
  
  /* 标签样式优化 */
  .ant-tag {
    margin-right: 4px;
    font-weight: 500;
    padding: 0 8px;
    line-height: 22px;
    height: 22px;
  }
  
  /* 总利润统计样式 */
  .profit-summary {
    margin-bottom: 16px;
  }
  
  .profit-text {
    font-size: 14px;
  }
</style> 